package com.matrix.marketing.controller;

import com.matrix.api.marketing.dto.DynamicCouponGrantDTO;
import com.matrix.api.marketing.dto.MerchantCouponGrantRequestDTO;
import com.matrix.api.marketing.vo.UserCouponVO;
import com.matrix.api.merchant.MerchantApi;
import com.matrix.api.merchant.vo.ShopInfoVO;
import com.matrix.common.domain.Result;
import com.matrix.common.exception.BusinessException;
import com.matrix.marketing.service.impl.MarketingInternalServiceImpl;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import org.apache.dubbo.config.annotation.DubboReference;
import org.springframework.web.bind.annotation.*;

/**
 * @author 有点甜
 * @since 2025/8/1
 */
@RestController
@RequestMapping("/merchant/marketing")
@RequiredArgsConstructor
public class MarketingMerchantController {

    @DubboReference(check = false)
    private MerchantApi merchantApi;

    private final MarketingInternalServiceImpl marketingInternalServiceImpl;

    @PostMapping("/coupon/grant")
    public Result<UserCouponVO> grantDynamicCoupon(
            @RequestHeader("X-User-ID") Long merchantUserId,
            @RequestBody @Valid MerchantCouponGrantRequestDTO request) {

        ShopInfoVO shopInfo = merchantApi.getShopInfoByUserId(merchantUserId);
        if (shopInfo == null) {
            throw new BusinessException("您尚未开店,无法进行操作");
        }

        DynamicCouponGrantDTO.CouponType internalType = request.getCouponType() == MerchantCouponGrantRequestDTO.CouponType.NO_THRESHOLD ?
                DynamicCouponGrantDTO.CouponType.NO_THRESHOLD : DynamicCouponGrantDTO.CouponType.THRESHOLD;

        DynamicCouponGrantDTO internalDto = DynamicCouponGrantDTO.builder()
                .targetUserId(request.getTargetUserId())
                .merchantUserId(merchantUserId)
                .shopId(shopInfo.getShopId())
                .title(request.getTitle())
                .couponType(internalType)
                .thresholdAmount(request.getThresholdAmount())
                .discountAmount(request.getDiscountAmount())
                .build();

        UserCouponVO userCouponVO = marketingInternalServiceImpl.grantDynamicCouponByMerchant(internalDto);

        return Result.success(userCouponVO);
    }
}
